package com.hongshan.wallet.core.login

import android.app.Application
import android.databinding.ObservableField
import android.os.Bundle
import android.view.View
import com.hongshan.wallet.Constant
import com.hongshan.wallet.MyApplication
import com.hongshan.wallet.base.MyViewModel
import com.hongshan.wallet.http.HttpClient
import com.hongshan.wallet.router.RouterIndex
import com.hongshan.wallet.router.go
import com.hongshan.wallet.toast
import com.hongshan.wallet.tryRun
import com.hongshan.wallet.util.MyActivityManager
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.async
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

/**
 * Copyright Qiandai Ltd.
 * Copyright (c) 2019
 * All rights reserved
 *
 * @project  : Wallet
 * @package  : com.example.wallet.core.register
 * @author   : Administrator
 * @data     : 2019/3/18
 * @email    : zhangxx@baihang-china.com
 */
class RegisterViewModel(application: Application) : MyViewModel(application) {

    val tel: ObservableField<String> = ObservableField("")
    val smsCode: ObservableField<String> = ObservableField("")
    val pwd: ObservableField<String> = ObservableField("")
    val invitationCode: ObservableField<String> = ObservableField("")
    val sendTime: ObservableField<String> = ObservableField("发送验证码")
    val sendStatus: ObservableField<Boolean> = ObservableField(true)

    val register = View.OnClickListener {
        if (check()) return@OnClickListener
        showLoading.call()
        val json = Constant.gson.toJsonTree(
            mapOf(
                "mobile" to tel.get()?.trim(),
                "code" to smsCode.get()?.trim(),
                "invite_code" to invitationCode.get()?.trim()
            )
        )
        GlobalScope.launch(Dispatchers.Main) {
            val result = GlobalScope.async(Dispatchers.IO) {
                tryRun { HttpClient.httpApi.register(json).execute() }
            }
            val body = result.await()?.body()
            showSuccess.call()
            if (body?.code == 0){
                val bundle = Bundle()
                bundle.putString("tel",tel.get())
                this@RegisterViewModel.activityResult.value = bundle
                this@RegisterViewModel.finish.call()
                MyApplication.user = body.data
                MyApplication.user?.save()
                MyActivityManager.getActivity(LoginActivity::class.java)?.finish()
                go(RouterIndex.MAIN)
            } else{
                toast(body?.msg)
            }
        }
    }

    val send = View.OnClickListener {
        val telStr = tel.get()
        if (checkTel()) return@OnClickListener
        val result = GlobalScope.async(Dispatchers.IO) {
            tryRun { HttpClient.httpApi.sendSms(telStr!!).execute() }
        }
        GlobalScope.launch(Dispatchers.Main) {
            val response = result.await() ?: return@launch
            if (response.isSuccessful) {
                if (response.body()?.code == 0) {
                    toast("发送成功")
                    sendStatus.set(false)
                    for (num in 60 downTo 1) {
                        sendTime.set("${num}s")
                        delay(1000)
                    }
                    sendTime.set("发送验证码")
                    sendStatus.set(true)
                } else {
                    toast(response.body()?.msg)
                }
            }
        }
    }

    private fun check(): Boolean {
        val code = smsCode.get()?.trim()
//        val invitaCode = invitationCode.get()
        if (checkTel()) return true
        if (!"\\d{6}".toRegex().matches(code!!)) {
            toast("短信验证码格式错误")
            return true
        }
//        if (!"\\w{6}".toRegex().matches(invitaCode!!)) {
//            toast("邀请码格式错误")
//            return true
//        }
        return false
    }

    private fun checkTel(): Boolean {
        val telStr = tel.get()?.trim()
        if (telStr == null || !Constant.Regex.TEL.toRegex().matches(telStr)) {
            toast("手机号码格式错误")
            return true
        }
        return false
    }

    val protocol = View.OnClickListener {

    }
}